package com.yanshaohui.controller;

import com.yanshaohui.bean.Person;
import com.yanshaohui.repository.PersonRepository;
import org.jboss.logging.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.ReactiveMongoTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.reactive.function.BodyInserters;
import org.springframework.web.reactive.function.server.ServerResponse;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.stream.Stream;

/**
 * Created by TS-Ysh on 2018-05-14.
 */
@RestController
public class ReactMongoJpaController {

    private final Logger logger = Logger.getLogger(getClass());

    @Autowired
    private PersonRepository personRepository;

    @RequestMapping("/mongo2/save/person/{id}/{name}")
    public Mono<Person> savePerson(@PathVariable("id") Long id, @PathVariable("name") String name){
        return personRepository.save(new Person(id,name,1,"天马座",26));
    }

    @RequestMapping("/mongo2/get/person/{id}")
    public Mono<Person> getPerson(@PathVariable("id") Long id){
        return personRepository.findById(id);
    }

    @RequestMapping("/mongo2/get/persons")
    public Flux<Person> getAll(){
        return personRepository.findAll();
    }

    /**
     * 使用Reactive类型的@RequestParam Mono<String>参数不支持
     * java.lang.IllegalStateException: RequestParamMethodArgmentResolver doesn't support reactive type wrapper: reactor.core.publisher.Mono<java.lang.String>
     *     但官网样例是说是可以的，奇怪：https://spring.io/blog/2016/11/28/going-reactive-with-spring-data
     * @param name
     * @return
     */
    @RequestMapping("/mongo2/findByName/persons")
    public Flux<Person> findByName(@RequestParam String name){
        return personRepository.findByName(Mono.just(name));
    }

    @RequestMapping("/mongo2/findBySexAndAge/persons")
    public Flux<Person> findBySexAndAge(@RequestParam Integer sex,@RequestParam Integer age){
        return personRepository.findBySexAndAge(sex,age);
    }

}
